package com.claude.mainactivity;

import java.util.ArrayList;

import org.json.JSONObject;

import com.android.volley.VolleyError;
import com.claude.bean.Cron;
import com.claude.bean.Session;
import com.claude.bean.Subject;
import com.claude.communication.RequestManager;
import com.claude.communication.RequestNode;
import com.claude.communication.RequestNode.RequestListener;
import com.claude.sql.LessionTableManager;
import com.claude.sql.SQLManager;
import com.claude.sql.SessionTableManager;
import com.claude.util.Configure;
import com.claude.util.Parser;
import com.claude.util.QueryParser;
import com.claude.util.TimeTool;
import com.special.ResideMenuDemo.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ClassSelectActivity extends Activity {
	final private int CLASS_REQUEST = 1;
	private MyApplication mMyApplication = null;
	private Configure configure = null;
	private int mItemResource = R.layout.my_list_item;
	private ListView mListView = null;
	private Subject subject = null;
	private RequestManager mRequestManager = null;
	private RequestListener mRequestListener = null;
	private ArrayList<Session> mArrayList = null;
	private ArrayAdapter<Session> mArrayAdapter = null;
	private OnItemClickListener mOnItemClickListener = null;
	private ProgressDialog mProgressDialog = null;
	private SQLiteDatabase mSQLiteDatabase = null;
	private SessionTableManager mSessionTableManager = null;
	private LessionTableManager mLessionTableManager = null;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_class);

		showDialog();

		mMyApplication = (MyApplication) getApplication();
		configure = Configure.getInstance();
		subject = mMyApplication.getCurSubject();
		if (mMyApplication.getOfflineState()) {
			getResource();
		} else {
			initResource();
			mProgressDialog.dismiss();
		}
	}

	public void onStop() {
		if (mRequestManager != null) {
			mRequestManager.stopRequest();
		}
		super.onStop();
	}

	private void showDialog() {
		mProgressDialog = new ProgressDialog(ClassSelectActivity.this);
		mProgressDialog.setCanceledOnTouchOutside(false);
		mProgressDialog.show();
	}

	private void initResource() {
		mSQLiteDatabase = new SQLManager(ClassSelectActivity.this)
				.getReadableDatabase();
		mSessionTableManager = new SessionTableManager(mSQLiteDatabase);
		String sqlStatement = String
				.format("select * from session where suno = '%s' and leno in(select leno from lession where leweek = '%d')",
						new Object[] { subject.getSubjectNumber(),
								TimeTool.getWeek() });
		Cursor cursor = mSessionTableManager.rawQueryStatement(sqlStatement);
		mArrayList = QueryParser.getSessions(cursor);
		if (mArrayList != null) {
			mMyApplication.setSessions(mArrayList);
			initView();
		} else {
			Toast.makeText(ClassSelectActivity.this, "该课程下没有班级",
					Toast.LENGTH_SHORT).show();
			gotoBack();
		}
	}

	private void getResource() {
		mRequestListener = new MyRequestListener();
		mRequestManager = RequestManager.newInstance();
		RequestNode requestNode = new RequestNode(getParamsWithClass(),
				mRequestListener, null, CLASS_REQUEST);
		mRequestManager.addRequest(requestNode);
		mRequestManager.startRequest();
	}

	private String getParamsWithClass() {
		return String.format(configure.getSubjectUrl()
				+ "?teacherNumber=%s&subjectNumber=%s", mMyApplication
				.getUser().getTeacherNumber(), subject.getSubjectNumber());
	}

	private void initView() {
		mArrayAdapter = new ArrayAdapter<Session>(ClassSelectActivity.this,
				mItemResource, mArrayList);
		mListView = (ListView) findViewById(R.id.listview);
		mListView.setAdapter(mArrayAdapter);
		mOnItemClickListener = new MyOnItemClickListener();
		mListView.setOnItemClickListener(mOnItemClickListener);
	}

	class MyRequestListener implements RequestListener {

		public void onSuccess(JSONObject jsonObject, int tag) {
			if (tag == CLASS_REQUEST) {
				mArrayList = Parser.getClasses(jsonObject);
				if (mArrayList != null) {
					mProgressDialog.dismiss();
					mMyApplication.setSessions(mArrayList);
					initView();
				} else {
					Toast.makeText(ClassSelectActivity.this, "该课程下没有班级",
							Toast.LENGTH_SHORT).show();
					mProgressDialog.dismiss();
					gotoBack();
				}
			}
		}

		public void onError(VolleyError volleyError, int tag) {
			if (tag == CLASS_REQUEST) {
				Toast.makeText(ClassSelectActivity.this, "网络情况不佳",
						Toast.LENGTH_SHORT).show();
				mProgressDialog.dismiss();
				gotoBack();
			}
		}
	}

	class MyOnItemClickListener implements OnItemClickListener {

		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Session session = mArrayList.get(arg2);
			mMyApplication.setCurSession(session);
			if (!mMyApplication.getOfflineState()) {
				getCronInforOffLine(session.getSessionNumber(),
						String.valueOf(TimeTool.getWeek()));
			}
			gotoCheckStudent();
		}
	}

	public void getCronInforOffLine(String sessionid, String week) {
		if (mSQLiteDatabase == null) {
			mSQLiteDatabase = new SQLManager(ClassSelectActivity.this)
					.getReadableDatabase();
		}
		mLessionTableManager = new LessionTableManager(mSQLiteDatabase);
		// TODO
		if (mSessionTableManager == null) {
			mSessionTableManager = new SessionTableManager(mSQLiteDatabase);
		}
		Cursor sessionCursor = mSessionTableManager.search(sessionid);
		if (sessionCursor != null) {
			sessionCursor.moveToFirst();
			Cursor cursor = mLessionTableManager.search(sessionCursor
					.getString(sessionCursor.getColumnIndex("leno")), week);
			Cron cron = QueryParser.getCron(cursor);
			mMyApplication.setCron(cron);
		}
	}

	private void gotoCheckStudent() {
		Intent intent = new Intent();
		intent.setClass(ClassSelectActivity.this, CheckStudentActivity.class);
		ClassSelectActivity.this.startActivity(intent);
	}

	private void gotoBack() {
		Intent intent = new Intent();
		intent.setClass(ClassSelectActivity.this, SubjectSelectActivity.class);
		ClassSelectActivity.this.startActivity(intent);
	}
}
